package com.bajiao.app.shiro;

import com.bajiao.common.constant.CommonConstant;
import com.bajiao.common.system.util.JwtUtil;
import com.bajiao.entity.user.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前登录会员用户
 */
@Component
public class LoginUser {

	private static RedisTemplate redisTemplate;

	@Autowired
	public void setRedisTemplate(RedisTemplate redisTemplate) {
		LoginUser.redisTemplate = redisTemplate;
	}


	public static String getCurrentUserId(){

		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String token=request.getHeader("TOKEN");
		if(token==null){
			token="";
		}
		return JwtUtil.getUserId(token);
	}

	public static Object getCurrentUser(){

		User entity = null;

		//获取到当前线程绑定的请求对象
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		String id = (String) request.getAttribute(CommonConstant.SIGN_USER_ID);

		if(StringUtils.isNotBlank(id)){

			entity = (User) redisTemplate.boundValueOps(CommonConstant.SIGN_USER_ID + id).get();

		}

		return entity;

	}


}
